package org.brownflat.dbinit.upgrade;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * <p>Database Init &copy Rupert Jones 2013</p>
 *
 * @author rup
 */
public class UpgradeFileFinder implements UpgradeFinder {

    private final static Logger LOG = Logger.getLogger(UpgradeFileFinder.class);

    public Object[] find(String packageName, String pattern) {
        ArrayList<File> files = new ArrayList<File>();
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            assert classLoader != null;
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);
            List<File> dirs = new ArrayList<File>();
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                dirs.add(new File(resource.getFile()));
            }

            for (File directory : dirs) {
                files.addAll(findFiles(directory, packageName, pattern));
            }
            return files.toArray(new File[files.size()]);
        } catch(ClassNotFoundException cnfe) {
            LOG.error(cnfe);
        } catch (IOException e) {
            LOG.error(e);
        }
        return files.toArray();
    }

    /**
    * Recursive method used to find all classes in a given directory and subdirs.
    *
    * @param directory   The base directory
    * @param packageName The package name for classes found inside the base directory
    * @return The classes
    * @throws ClassNotFoundException
    */
    private List<File> findFiles(File directory, String packageName, String pattern) throws ClassNotFoundException {
        List<File> filesToReturn = new ArrayList<File>();
        if (!directory.exists()) {
            return filesToReturn;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                filesToReturn.addAll(findFiles(file, packageName + "." + file.getName(), pattern));
            } else if (file.getName().matches(pattern)) {
                filesToReturn.add(file);
            }
        }
        return filesToReturn;
    }
}
